// ------------------------------------------------------------------------------------------
// Licensed by Interprise Solutions.
// http://www.InterpriseSolutions.com
// For details on this license please visit  the product homepage at the URL above.
// THE ABOVE NOTICE MUST REMAIN INTACT.
// ------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Data;
using InterpriseSuiteEcommerceCommon;
using InterpriseSuiteEcommerceCommon.InterpriseIntegration.JSONLib;
using InterpriseSuiteEcommerceCommon.DTO;

namespace InterpriseSuiteEcommerceControls
{
    public class AddressControlHandler : IHttpHandler
    {
        private const string ACTION = "action";
        private const string ACTION_GET_STATES = "getStates";
        private const string ACTION_ADD_NEW = "new";

        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            string action = context.Request.QueryString[ACTION];

            switch (action)
            {
                case ACTION_GET_STATES:
                    string country = HttpUtility.UrlDecode(context.Request.QueryString["country"]);
                    if (!string.IsNullOrEmpty(country))
                    {
                        GetStatesAndFlushResponse(country, context);
                    }
                    break;
                case ACTION_ADD_NEW:
                    break;
            }
        }

        private void GetStatesAndFlushResponse(string forCountry, HttpContext onContext)
        {
            onContext.Response.Clear();

            CountryAddressDTO requestedCountry = CountryAddressDTO.Find(forCountry);
            if (null != requestedCountry)
            {
                JSONSerializer serializer = new JSONSerializer(SerializeOption.All);
                List<StateDTO> states = requestedCountry.GetStates();
                string response = serializer.SerializeArray(states);

                onContext.Response.Write(response);
            }
            
            onContext.Response.Flush();
            onContext.Response.End();
        }

        #endregion
    }
}
